<script setup>
import Header from '@/components/header/Header.vue'
import Tab from './components/Tab.vue'
import Card from './components/Card.vue'
import MallCard from './components/MallCard.vue'
import HaishuaCard from './components/HaishuaCard.vue'
import PandaCard from './components/PandaCard.vue'
import {computed, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import api from '@/api/index.js'
import {useKeepalive} from '@/hooks/useKeepalive.js'
import {closeToast, showLoadingToast} from "vant";

defineOptions({
  name: 'OrderList',
})
const appValue = ref(0)
const apps = [
  {text: '商超', name: '商超', value: 1},
  {text: '票务', name: '票务', value: 0},
  {text: '蛋糕', name: '蛋糕', value: 3},


]
const showPicker = ref(false)
const needSaveRoute = [
  'scenicOrderDetail',
  'pandaOrderDetail',
  'scenicDetail',
  'hotelDetail',
]
const {scrollYEle} = useKeepalive(needSaveRoute, 'OrderList')

const list = ref([])
const error = ref(false)
const loading = ref(true)
const finished = ref(true)
const refreshing = ref(false)
const totalCount = ref(0)
const route = useRoute()

const type = 'mall'

let getOrderList = null
const title = ref('')
const initPage = () => {
  getOrderList = api.getMallOrderList
  title.value =route.query.isConsumption==0? '自助消费订单': '社区商店订单'
}
initPage()

const params = {
  pageNum: 1,
  pageSize: 10,
  isConsumption:route.query.isConsumption
}
const ordinaryFinished = ref(false)
const _getOrderList = () => {
  error.value = false
  loading.value = true
  // 订单状态 0-待支付 1-待使用/待发货 2-待收货 3-已完成 4-退款单 6-订单已取消 11 订单异常

  getOrderList(params)
      .then((res) => {
        list.value = [...list.value, ...res.data]
        if (res.data.length < params.pageSize) {
          finished.value = true
        }
        totalCount.value = list.value.length
        params.pageNum += 1
        ordinaryFinished.value = false
        loading.value = false
        refreshing.value = false
        console.log('getOrderList resp')
      })
      .catch(() => {
        error.value = true
        loading.value = false
      })
      .finally(() => {
        refreshing.value = false
        loading.value = false
      })
  //合并状态1和2的订单
  if (params.status == 1) {
    var params2 = JSON.parse(JSON.stringify(params))
    params2.status = 2
    getOrderList(params2)
        .then((res) => {
          list.value = [...list.value, ...res.data]
          if (res.data.length < 10) {
            finished.value = true
          }
          totalCount.value = list.value.length
          // params.pageNum += 1
          ordinaryFinished.value = false
          loading.value = false
        })
        .catch(() => {
          error.value = true
          loading.value = false
        })
        .finally(() => {
          refreshing.value = false
        })
  }
}

// 普通订单 订单状态:0-待支付 1-待核销 2-已核销 3-已取消 4-退款中 5-已退
// 熊猫订单 订单状态 0-待支付 1-待使用/待发货 2-待收货 3-已完成 4-退款单 6-订单已取消

const onLoad = () => {
  console.log('onLoad')
  loading.value = true
  finished.value = false
  _getOrderList()
}
onLoad()

const onRefresh = () => {
  loading.value = true
  resetting()
}

const resetting = () => {
  params.pageNum = 1
  list.value = []
  ordinaryFinished.value = false
  onLoad()
}

const changeTab = (key) => {
  loading.value = true
  params.status = key
  resetting()
}

watch(error, (val) => {
  if (!val) {
    loading.value = true
    resetting()
  }
})

const isShowVanList = computed(() => {
  if (list.value.length) {
    return true
  }
  if (loading.value || refreshing.value) {
    return true
  }
  if (error.value) {
    return true
  }
  return false
})

// 刷新页面数据
const cancelOrderResetting = () => {
  resetting()
}
const h5Url = import.meta.env.VITE_COMMUNITY_STORE_URL
const siteCode = import.meta.env.VITE_R29_SITECODE

function onConfirm(e) {
  console.log(e)
  showPicker.value=false
  if (e.value === 1) {

    return
  }
  console.log('asdaxxx')
  showLoadingToast()
  api.getTmpToken().then(res => {

    console.log('getTmpToken',res)
    if (res.code === '200') {
      const params = `?siteCode=${siteCode}&tmpToken=${res.data}&redirectUrl=${location.href}`
      if (e.value === 0) {
        window.location.href = `${h5Url}#/TicketOrderListScreen${params}`
      } else if (e.value === 2) {
        window.location.href = `${h5Url}#/FlowerOrdersScreen${params}`
      }
      else if (e.value === 3) {
        window.location.href = `${h5Url}#/CakeOrderListScreen${params}`
      }
    }
  }).finally(()=>closeToast())


}
</script>

<template>
  <div class="order">
    <div style="display: flex;flex-direction: row;align-items: center">
      <Header :title="title" :back="true" path="/mine" style="flex-grow: 1"/>
      <div
          v-if="route.query.isConsumption==1"
          style="padding-right: 20px">
        <div class="location" @click="()=>{
          console.log('click1asdasd')
          showPicker=true
        }">

          <span>{{ apps[appValue].text }}</span>
        </div>
      </div>
    </div>

    <Tab :type="type" @changeTab="changeTab"/>
    <div class="content" ref="scrollYEle">
      <van-pull-refresh
          class="van_pull_refresh"
          v-model="refreshing"
          @refresh="onRefresh"
      >
        <van-list
            v-if="isShowVanList"
            v-model:loading="loading"
            v-model:error="error"
            :finished="finished"
            finished-text="没有更多了"
            error-text="出错了，点击重试"
            @load="onLoad"
        >
          <MallCard
              class="list"
              v-for="item in list"
              :key="item"
              :data="item"
              @cancelOrderResetting="cancelOrderResetting"
              :type="type"
          />
        </van-list>

        <div v-else>
          <div class="none">
            <img
                class="none_img"
                src="@/assets/images/index/none1.png"
                alt=""
            />
            <span>暂无订单信息，去逛逛</span>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>

  <van-popup
      v-if="showPicker"
      v-model:show="showPicker"
      round
      position="bottom"
  >

    <van-action-sheet
        v-model:show="showPicker"
        :actions="apps"
        title="选择模块"
        @select="onConfirm"
    />
  </van-popup>
</template>

<style scoped lang="scss">
.order {
  display: flex;
  flex-direction: column;
  height: 100%;

  .content {
    flex: 1;
    background: #f9f8f3;
    overflow-y: auto;
    padding-top: 1.5rem;

    .van_pull_refresh {
      min-height: 100%;

      .list {
        margin: 0 1.5rem 1.5rem 1.5rem;
      }

      .none {
        display: flex;
        flex-direction: column;
        align-items: center;

        .none_img {
          width: 6rem;
          margin: 14.4rem 0 1rem 0;
        }

        span {
          font-size: 1.4rem;
          color: #666666;
        }
      }
    }
  }
}

.location {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 3.5rem;
  //width: 6.5rem;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2rem;
  flex-shrink: 0;
  padding-right: 10px;
  padding-left: 10px;
  color: #fffef8;

  img {
    width: 1.6rem;
    height: 1.6rem;
    margin-right: 0.02rem;
  }

  span {
    padding: 0 0.02rem;
  }
}
</style>